package com.idea.relax.redis.limiter.client;

import com.idea.relax.redis.limiter.constant.RedisLimiterConstant;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;

import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: 沉香
 * @date: 2023/2/14
 * @description:
 */
@AllArgsConstructor
public class RedisLimiterClientImpl implements RedisLimiterClient {

	private final StringRedisTemplate redisTemplate;

	private final RedisScript<Long> limiterRedisScript;

	@Override
	public boolean isAllowed(String key, long count, long period, TimeUnit timeUnit) {
		List<String> keys = Collections.singletonList(key);
		long periodToMillis = timeUnit.toMillis(period);
		long now = Instant.now().toEpochMilli();
		long expired = now - periodToMillis;
		Long result = redisTemplate.execute(limiterRedisScript, keys, now, periodToMillis, count, expired);
		return result != null && result != RedisLimiterConstant.LIMITER_FAIL_CODE;
	}

}
